//
//  AnHaoViewController.m
//  安好
//
//  Created by lianchuang on 14-11-5.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "AnHaoViewController.h"
#import "XHDrawerController.h"
#import "LeftViewController.h"
#import "BaseNavigation.h"
#import "UserModel.h"
#import "AnhaoTableViewCell.h"
#import "HealthRecordLogViewController.h"
#import "MyConsultListViewController.h"
#import "TiJianRootViewController.h"
#import "RegistrationViewController.h"
#import "MainViewController.h"
#import "ChatContent.h"
#import "PeerList.h"
#import "ConsultList.h"
#import "YXJSON.h"
#import "MyPeerListViewController.h"
#import "SDImageView+SDWebCache.h"
#import "ConsultViewController.h"
#import "LoginViewController.h"
#import "LCStatusBarOverlay.h"
#import "MyHealthLogViewController.h"
#import "SubscibeViewController.h"
#import "SecretaryViewController.h"
#import "ConsultingChatViewController.h"
#import "FMDatabaseQueue.h"
#import "SystemMessageCenter.h"
#import "ZhengZhuangViewController.h"
#import "UIImageView+AFNetworking.h"



@interface AnHaoViewController ()<UITableViewDataSource,UITableViewDelegate,LCStatusBarDelegate>
{
    BOOL NaviButonBool;
    NSInteger healthViewNum;
}
@end

@implementation AnHaoViewController
{
//    NSArray *peerArray;
//    NSArray *noPeerArray;
    NSInteger peerCount;
    NSInteger noPeerCount;
    UIImageView *leftImag;
    NSInteger haveNoReadSystemMessage;
    NSInteger haveNoReadNewsMessage;
}
- (void)refreshNewInfo
{
    peerCount=0;
    noPeerCount=0;
    peerCount=[PeerList readUnreadCount];
    noPeerCount=[ConsultList readUnreadCount];
    if (peerCount>0||noPeerCount>0||!peerCount||!noPeerCount) {
        [self.anhaoTableView reloadData];
    }
}
- (void)receiveMessage:(AppDelegate *)appD Message:(id)message
{
    
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //判断同行or非同行 。type=1同行；type=2医患关系。
    //    ConsultList *consultList=[[ConsultList alloc]initWithDictionary:dict];
    NSString *readStatus;
    if ([[dict objectForKey:@"type"] intValue] == 1) {
        readStatus=@"1";
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                //加入耗时操作
                NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                CGSize size;
                if ([[messageDic valueForKey:@"pic"]length]>0) {
                    size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                    [ChatContent insertChatMessageItem:[messageDic JSONString] Andsuccess:@"1" AndMessageDirection:@"2"];
                }
                else{
                    [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                }
            });
            if ([PeerList updatePeerList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
//                peerArray=[PeerList readAllPeerListItem];
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];

                [self refreshNewInfo];
            }
            
        });
    }else
    {
        readStatus=@"1";
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //加入耗时操作
                NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                
                if ([ConsultList updateConsultList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                    //                noPeerArray=[ConsultList readAllConsultList];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                    [self refreshNewInfo];
                    NSString *meth=[NSString stringWithFormat:@"%@",[dict valueForKey:@"method"]];
                    if ([meth isEqualToString:@"9"]) {
                        return;
                    }
                }
                
                
                
                CGSize size;
                if ([[messageDic valueForKey:@"pic"]length]>0) {
                    size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                    [ChatContent insertChatMessageItem:[messageDic JSONString] Andsuccess:@"1" AndMessageDirection:@"2"];
                }
                else{
                    [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                }
            });
        });
    }
}
- (void)receiveRemoteNotificationMessage:(AppDelegate *)appD Message:(id)message
{
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //遍历消息内容数组，排序后将消息插入数据库（如果和当前用户是同一人，并展示聊天消息）
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *sqlPath=[docPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
    //    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    dispatch_async(q1, ^{
        
        
        NSArray * array1 = [[[dict objectForKey:@"history"] allKeys]sortedArrayUsingSelector:@selector(compare:)];
        for (int index=0; index<array1.count; index++) {
            NSString *keys=[array1 objectAtIndex:index];
            if([[[[dict objectForKey:@"history"] objectForKey:keys] objectForKey:@"action"] isEqualToString:@"send"])
            {
                //在其他界面收到聊天消息，只进行存取数据（2个表）
                NSMutableDictionary *MutDic=[NSMutableDictionary dictionaryWithDictionary:[[dict objectForKey:@"history"] objectForKey:keys]];
                [MutDic setValue:@"2" forKey:@"messageDirection"];
                NSString *messageType;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"message"] length] > 0) {
                    messageType = @"1";
                } else if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"pic"] length] > 0) {
                    messageType = @"2";
                } else {
                    messageType = @"3";
                }
                [MutDic setValue:messageType forKey:@"messageType"];
                //判断同行or非同行 。type=1同行；type=2医患关系。
                NSString *readStatus;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys]  objectForKey:@"type"] intValue] == 1) {
                    readStatus=@"1";
                    
                    
                    //加入耗时操作
                    NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                    CGSize size;
                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                        [queue inDatabase:^(FMDatabase *db) {
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                        }];
                        
                    }
                    else{
                        [queue inDatabase:^(FMDatabase *db) {
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];

                        }];
                    }
                    [queue inDatabase:^(FMDatabase *db) {
                        [PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];

                    }];
                    
//                    [queue inDatabase:^(FMDatabase *db) {
//                        [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
//                        if ([PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
//                        }
//                    }];
                }else
                {
//                    if ([ConsultList isExistItem:[[dict objectForKey:@"history"] objectForKey:keys] AndDb:[MyFMDB openDB]]) {
//                        readStatus=@"1";
//                    }else
//                    {
                        readStatus=@"1";
//                    }
                    
                    
                    //加入耗时操作
                    NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                    CGSize size;
                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                        
                        [queue inDatabase:^(FMDatabase *db) {
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                            if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                            }
                        }];
                    }
                    else{
                        [queue inDatabase:^(FMDatabase *db) {
                            
                            if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                                NSString *meth=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"method"]];
                                if ([meth isEqualToString:@"9"]) {
                                    return;
                                }
                                [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
                            }
                            
                        }];
                    }
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshNewInfo ];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            [self.anhaoTableView reloadData];
        });

    });
    
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [[LCStatusBarOverlay shared] hidenMessageLabel];
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=nil;
}
- (AppDelegate *)app
{
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=self;
    return app;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    LCStatusBarOverlay *lcStatus=[LCStatusBarOverlay shared];
    [lcStatus hidenMessageLabel];
    lcStatus.statusDelegate=self;
    [self app];
    [self ViewWithLeftButton];
    [self refreshNewInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NaviButonBool = NO;
    self.navigationItem.title = @"你若安好便是晴天";
    /**
     *  加载tableView
     */
    [self ViewWithAnhaoTableView];
    /**
     *  加载button
     */

    [self viewWithAnhaoHeaderView];
    peerCount=0;
    noPeerCount=0;
//    peerArray=[[NSArray alloc]init];
//    noPeerArray=[[NSArray alloc]init];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(crowdout) name:@"CrowdOut" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doShowRedPoint) name:kDidGetAndStoreSystemNotification object:nil];
    [self doShowRedPoint];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSHowSubscibeRedPoint) name:kDidGetAndStoreNewsNotification object:nil];
    [self doSHowSubscibeRedPoint];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"HiddenLeftUser" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        leftImag.hidden = YES;
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"ShowLeftUser" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        leftImag.hidden = NO;
    }];
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
//    if (IOS8_OR_LATER) {
//        BOOL isFromHealth = [HKHealthStore isHealthDataAvailable];
//        if (isFromHealth == YES) {
//            self.healthStore = [[HKHealthStore alloc]init];
//            
//            
//            NSSet *writeDataTypes = [self dataTypesToWrite];
//            NSSet *readDataTypes = [self dataTypesToRead];
//            
//            [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
//                
//                if (!success) {
//                    NSLog(@" %@", error);
//                    
//                    return;
//                }
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self updateUsersAgeLabel];
//                });
//            }];
//            
//        }
//    }
//#endif
    
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"DisMissView" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            [self performSelector:@selector(presentDuihuaView) withObject:nil afterDelay:0.5];
        }];
        
    }];
    
}
//发出通知--到达指定页面
-(void)presentDuihuaView
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"yongyao1" object:nil];
}
- (void)crowdout
{
    leftImag.frame = CGRectMake(0,0, 23, 23);
    leftImag.layer.cornerRadius = 0;
    leftImag.layer.borderWidth = 0;
    leftImag.image = [UIImage imageNamed:@"安好_个人@2x"];
}
//- (NSSet *)dataTypesToWrite {
//    HKQuantityType *dietaryCalorieEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed];
//    HKQuantityType *activeEnergyBurnType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
//    HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
//    HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
//    
//    return [NSSet setWithObjects:dietaryCalorieEnergyType, activeEnergyBurnType, heightType, weightType, nil];
//}
//- (NSSet *)dataTypesToRead {
//    HKQuantityType *dietaryCalorieEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed];
//    HKQuantityType *activeEnergyBurnType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
//    HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
//    HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
//    HKCharacteristicType *birthdayType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth];
//    HKCharacteristicType *biologicalSexType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];
//    
//    return [NSSet setWithObjects:dietaryCalorieEnergyType, activeEnergyBurnType, heightType, weightType, birthdayType, biologicalSexType, nil];
//}
//
//- (void)updateUsersAgeLabel {
//    // Set the user's age unit (years).
//    NSLog(@"%@", NSLocalizedString(@"Age (yrs)", nil));
//    
//    NSError *error;
//    NSDate *dateOfBirth = [self.healthStore dateOfBirthWithError:&error];
//    
//    if (!dateOfBirth) {
//        NSLog(@"Either an error occured fetching the user's age information or none has been stored yet. In your app, try to handle this gracefully.");
//        
//        NSLog(@"%@", NSLocalizedString(@"Not available", nil));
//    }
//    else {
//        // Compute the age of the user.
//        NSDate *now = [NSDate date];
//        
//        NSDateComponents *ageComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:dateOfBirth toDate:now options:NSCalendarWrapComponents];
//        
//        NSUInteger usersAge = [ageComponents year];
//        
//        NSLog(@"%@", [NSNumberFormatter localizedStringFromNumber:@(usersAge) numberStyle:NSNumberFormatterNoStyle]);
//    }
//}

- (void)doShowRedPoint{//安好秘书
    if ([[SystemMessageCenter instance] isHaveNoReadedSystemMessage]) {//有没读的
        haveNoReadSystemMessage = YES;
    }
    else{
        haveNoReadSystemMessage = NO;
    }
    [self.anhaoTableView reloadData];
}

- (void)doSHowSubscibeRedPoint{//安好订阅
    BOOL isHaveNewsNoRead = [[SystemMessageCenter instance] isHaveNoReadSubscibeNews];
    if (isHaveNewsNoRead == YES) {
        haveNoReadNewsMessage = YES;
    }
    else{
        haveNoReadNewsMessage = NO;
    }
    [self.anhaoTableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isfrist"]) {
        
        int stauts = [UIUtils networkMonitoring];
        if (stauts == 0) {
            [[AppDelegate app]viewHiddenWifiView];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isfrist"];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)ViewWithAnhaoTableView
{
    self.anhaoTableView.frame = CGRectMake(0, -1, kScreenWidth, kScreenHeight-iOS7TopMargin-TABBAR_HEIGHT+1);
    self.anhaoTableView.delegate = self;
    self.anhaoTableView.dataSource = self;
    self.anhaoTableView.showsHorizontalScrollIndicator = NO;
    self.anhaoTableView.showsVerticalScrollIndicator = NO;
    [self.anhaoTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (kScreenWidth == 320){
    self.anhaoHeaderView = [[[NSBundle mainBundle]loadNibNamed:@"AnhaoHeaderView" owner:self options:nil] objectAtIndex:0];
    }else if (kScreenWidth == 375){
    self.anhaoHeaderView = [[[NSBundle mainBundle]loadNibNamed:@"AnhaoHeaderView" owner:self options:nil] objectAtIndex:1];
    }else{
    self.anhaoHeaderView = [[[NSBundle mainBundle]loadNibNamed:@"AnhaoHeaderView" owner:self options:nil] objectAtIndex:2];
    }
    self.anhaoHeaderView.anhaoDelegate=self;
    if (kScreenWidth == 414) {
        self.anhaoHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 120);
        self.anhaoHeaderView.upImage.frame = CGRectMake(0, 109, kScreenWidth, 0.5);
        self.anhaoHeaderView.downImage.frame = CGRectMake(0, 119, kScreenWidth, 0.5);
    }else{
        self.anhaoHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 88);
        self.anhaoHeaderView.upImage.frame = CGRectMake(0, 77, kScreenWidth, 0.5);
        self.anhaoHeaderView.downImage.frame = CGRectMake(0, 87, kScreenWidth, 0.5);
    }
    if (kScreenWidth == 320) {
        self.anhaoHeaderView.AnhaoScrollView.contentSize = CGSizeMake(380, 0);
    }else if (kScreenWidth == 375){
        self.anhaoHeaderView.AnhaoScrollView.contentSize = CGSizeMake(445, 0);
    }else{
        self.anhaoHeaderView.AnhaoScrollView.contentSize = CGSizeMake(500, 0);
    }
    self.anhaoHeaderView.AnhaoScrollView.backgroundColor = [UIColor clearColor];
    self.anhaoHeaderView.AnhaoScrollView.delegate = self;
    self.anhaoTableView.tableHeaderView = self.anhaoHeaderView;
    
//    self.anhaoFooterView = [[[NSBundle mainBundle]loadNibNamed:@"AnhaoFooterView" owner:self options:nil] lastObject];
//    self.anhaoTableView.tableFooterView = self.anhaoFooterView;
}
/**
 *  头视图的手势
 */
- (void)viewWithAnhaoHeaderView
{
    UITapGestureRecognizer * freeConsultationTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(freeConsultationView:)];
    [self.anhaoHeaderView.freeConsultationView addGestureRecognizer:freeConsultationTap];
    UITapGestureRecognizer * onlineMedicalTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onlineMedicalView:)];
    [self.anhaoHeaderView.onlineMedicalView addGestureRecognizer:onlineMedicalTap];
    UITapGestureRecognizer * phoneRegisteredTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(phoneRegisteredView:)];
    [self.anhaoHeaderView.phoneRegisteredView addGestureRecognizer:phoneRegisteredTap];
    
    UITapGestureRecognizer * healthLogTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(healthLogView:)];
    [self.anhaoHeaderView.healthLogView addGestureRecognizer:healthLogTap];
    
    UITapGestureRecognizer * symptomCheckTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(symptomCheckView:)];
    [self.anhaoHeaderView.symptomCheckView addGestureRecognizer:symptomCheckTap];
    
    

}
/**
 *  免费咨询
 *
 *  @param freeConsultationTap 免费咨询
 */
- (void)freeConsultationView:(UITapGestureRecognizer *)freeConsultationTap
{
    [self skipToConsult];
}
- (void)onlineMedicalView:(UITapGestureRecognizer *)onlineMedicalTap
{
    //体检
    TiJianRootViewController *tijianRoot = [[TiJianRootViewController alloc]init];
    [self.navigationController pushViewController:tijianRoot animated:YES];
}
- (void)phoneRegisteredView:(UITapGestureRecognizer *)phoneRegisteredTap
{
    // “挂号”
    RegistrationViewController *registration = [[RegistrationViewController alloc] init];
    [self.navigationController pushViewController:registration animated:YES];
}

- (void)healthLogView:(UITapGestureRecognizer *)healthLogTap{
    healthViewNum = 200;
    [self isLogin];
}
/**
 *  症状自查
 *
 *  @param sender
 */
-(IBAction)symptomCheckView:(id)sender{
    ZhengZhuangViewController *zhengZhuangViewController = [[ZhengZhuangViewController alloc] initWithNibName:@"ZhengZhuangViewController" bundle:nil];
    zhengZhuangViewController.title = @"症状自查";
    
    [self.navigationController pushViewController:zhengZhuangViewController animated:YES];
}

#pragma - mark 初始化
/**
 *  初始化跳转左视图的Button
 */
- (void)ViewWithLeftButton
{
    leftImag = [[UIImageView alloc]init];;
    leftImag.frame = CGRectMake(0,0, 23, 23);
    leftImag.userInteractionEnabled = YES;
    NSString * islogin =[[UserManager shareInstance]getUserIsLogin];
    if ([islogin length] == 0){
    leftImag.image = [UIImage imageNamed:@"安好_个人@2x"];
    }else{
        leftImag.frame = CGRectMake(0,0, 30, 30);
        leftImag.layer.masksToBounds = YES;
        leftImag.layer.cornerRadius = 15;
        leftImag.layer.borderWidth = 1.0;
        leftImag.layer.borderColor = [UIColor whiteColor].CGColor;
            BOOL isHaveUserImage = [[UserManager shareInstance]isHaveUserImage];
            if (isHaveUserImage == YES) {
                UIImage * userImage = [[UserManager shareInstance]getUserImage];
                leftImag.image  = userImage;
                if (self.isWright == NO) {
                    if ([leftImag.image isEqual: [UIImage imageNamed:@"默认头像"]]){
                    self.isWright = NO;
                    }else{
                    self.isWright = YES;
                    UserModel * usermodel = [[UserManager shareInstance]getUserInfo];
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                    NSString * uid = usermodel.uid;
                    NSString * imageName = [NSString stringWithFormat:@"%@.png",uid];
                    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
                    // 保存文件的名称
                    [UIImagePNGRepresentation(leftImag.image)writeToFile: filePath atomically:YES];
                    }
                }
            }else{
            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(upada) userInfo:nil repeats:NO];
                [self getImageByUrl];
        }
    }
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftButtonPush)];
    [leftImag addGestureRecognizer:tap];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImag];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0,0, 23, 23);
    [rightButton setImage:[UIImage imageNamed:@"公用_编辑@2x"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(pushHealth:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}
- (void)getImageByUrl
{
    
    
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        UserModel * usermodel = [[UserManager shareInstance]getUserInfo];
        [leftImag setImageWithURL:[NSURL URLWithString:usermodel.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
        
    });

}
- (void)upada
{
    
    if ([leftImag.image isEqual: [UIImage imageNamed:@"默认头像"]]){
        
        
    }else{

        UserModel * usermodel = [[UserManager shareInstance]getUserInfo];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString * uid = usermodel.uid;
        NSString * imageName = [NSString stringWithFormat:@"%@.png",uid];
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        // 保存文件的名称
        [UIImagePNGRepresentation(leftImag.image)writeToFile: filePath atomically:YES];
    }
}
#pragma - mark 跳转左视图的事件
/**
 *  判断是否登录
 *
 *  @param LeftButton wu
 */
- (void)leftButtonPush
{
     NaviButonBool = NO;
    [self isLogin];
}
- (void)pushHealth:(UIButton *)LeftButton
{
    NaviButonBool = YES;
    [self isLogin];
}
/**
 *  跳转到左视图
 */
- (void)Login
{
        if (healthViewNum == 200) {
        MyHealthLogViewController *myHealthLogVC = [[MyHealthLogViewController alloc] init];
        [self.navigationController pushViewController:myHealthLogVC animated:YES];
            healthViewNum = 100;
    }else{
        if (NaviButonBool) {
            HealthRecordLogViewController *healthRecordLogVC = [[HealthRecordLogViewController alloc] initWithNibName:@"HealthRecordLogViewController" bundle:nil];
            [self.navigationController pushViewController:healthRecordLogVC animated:YES];
            NaviButonBool = NO;
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LeftAnimation" object:nil];

            AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
            [app viewShowWifiView];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PushAnimation" object:(MainViewController *)[self.navigationController.viewControllers objectAtIndex:0]];
            [self.drawerController toggleDrawerSide:XHDrawerSideLeft animated:YES completion:NULL];
        }

    }
}
#pragma - mark tableView的代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (kScreenWidth == 414) {
        return 85;
    }else{
        return 70;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIdentifier = @"cellIdentifier";
    AnhaoTableViewCell *anhaoTablecell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (anhaoTablecell == nil) {
        if (kScreenWidth == 414) {
            anhaoTablecell = [[[NSBundle mainBundle] loadNibNamed:@"AnhaoTableViewCell" owner:self options:nil] lastObject];
        }else{
            anhaoTablecell = [[[NSBundle mainBundle] loadNibNamed:@"AnhaoTableViewCell" owner:self options:nil] firstObject];
        }
    }
    anhaoTablecell.userImageView.clipsToBounds = YES;
    anhaoTablecell.userImageView.layer.cornerRadius = 3;
    if (indexPath.row == 3)
    {
        if (kScreenWidth == 414) {
            anhaoTablecell.lineImageView.frame = CGRectMake(0, 84.5,kScreenWidth, 0.5);
        }else{
            anhaoTablecell.lineImageView.frame = CGRectMake(0, 69,kScreenWidth, 0.5);
        }
    }
    if (indexPath.row == 0) {
        anhaoTablecell.functionNamekLabel.text = @"我的咨询";
        if ([[ConsultList getTheLastOne] count]>0) {
            ConsultList *consult=[[ConsultList getTheLastOne] objectAtIndex:0];
            if (consult.username.length>0) {
                anhaoTablecell.describeLabel.text = [NSString stringWithFormat:@"%@：%@",consult.username,consult.message];
                
            }else
            {
                anhaoTablecell.describeLabel.text = [NSString stringWithFormat:@"%@",consult.message];
            }
            
        }else
        {
            anhaoTablecell.describeLabel.text = @"这里您将能看到有关你咨询过的问题列表";
        }
        anhaoTablecell.userImageView.image = [UIImage imageNamed:@"安好_咨询"];
        if (noPeerCount>0) {
            anhaoTablecell.redStatus.hidden=NO;
        }
        if (kScreenWidth == 414) {
            anhaoTablecell.lineImageView.frame = CGRectMake(90, 84.5,kScreenWidth, 0.5);
        }else{
            anhaoTablecell.lineImageView.frame = CGRectMake(70, 69,kScreenWidth, 0.5);
        }
    }else if (indexPath.row == 1){
        anhaoTablecell.functionNamekLabel.text = @"用户对话";
        if ([[PeerList getTheLastOne] count]>0) {
            PeerList *peer=[[PeerList getTheLastOne] objectAtIndex:0];
            anhaoTablecell.describeLabel.text=[NSString stringWithFormat:@"%@：%@",peer.username,peer.message];
        }
        else
        {
            anhaoTablecell.describeLabel.text = @"还未发起对话。马上发起与安友的对话吧";
        }
        anhaoTablecell.userImageView.image = [UIImage imageNamed:@"安好_对话"];
        if (peerCount>0) {
            anhaoTablecell.redStatus.hidden=NO;
        }
        if (kScreenWidth == 414) {
            anhaoTablecell.lineImageView.frame = CGRectMake(90, 84.5,kScreenWidth, 0.4);
        }else{
            anhaoTablecell.lineImageView.frame = CGRectMake(70, 69,kScreenWidth, 0.4);
        }
        
        //        anhaoTablecell.lineImageView.frame = CGRectMake(70, 69,kScreenWidth, 0.4);
    }else if (indexPath.row == 2){
        NSLog(@"anHaoViewController");
        anhaoTablecell.functionNamekLabel.text = @"安好秘书";
        SecretaryModel *model = [[SystemMessageCenter instance] getTheNewestSecretarySystemMessage];
        if (model) {
            anhaoTablecell.describeLabel.text = model.title;
        }
        else{
            anhaoTablecell.describeLabel.text = @"这里定期发布安好新版本、一手重要信息";
        }
        anhaoTablecell.userImageView.image = [UIImage imageNamed:@"安好_秘书"];
        anhaoTablecell.userImageView.clipsToBounds = YES;
        anhaoTablecell.userImageView.layer.cornerRadius = 3;
        if (kScreenWidth == 414) {
            anhaoTablecell.lineImageView.frame = CGRectMake(90, 84.5,kScreenWidth, 0.4);
        }else{
            anhaoTablecell.lineImageView.frame = CGRectMake(70, 69,kScreenWidth, 0.4);
        }
        if (haveNoReadSystemMessage) {
            anhaoTablecell.redStatus.hidden = NO;
        }
        else{
            anhaoTablecell.redStatus.hidden = YES;
        }
    }else{
        anhaoTablecell.functionNamekLabel.text = @"安好订阅";
        SubscibeModel *model = [[SystemMessageCenter instance] getTheNewestSecretaryNewsMessage];
        if (model) {
            anhaoTablecell.describeLabel.text = model.titleForSubscibe;
        }
        else{
            anhaoTablecell.describeLabel.text = @"还未订阅消息。马上关注您所关心的内容";
        }
        anhaoTablecell.userImageView.image = [UIImage imageNamed:@"安好_订阅"];
        anhaoTablecell.userImageView.clipsToBounds = YES;
        anhaoTablecell.userImageView.layer.cornerRadius = 3;
        if (haveNoReadNewsMessage) {
            anhaoTablecell.redStatus.hidden = NO;
        }
        else{
            anhaoTablecell.redStatus.hidden = YES;
        }
    }
    if (kScreenWidth == 414) {
        anhaoTablecell.describeLabel.frame = CGRectMake(90, 52, kScreenWidth- 100 - 100, 15);
    }else{
        anhaoTablecell.describeLabel.frame = CGRectMake(70, 40, kScreenWidth-80, 15);
    }
    return anhaoTablecell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnhaoTableViewCell *anhaoTableViewCell =(AnhaoTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    [anhaoTableViewCell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (indexPath.row==0) {
        
        NSString * userIsLogin =  [[UserManager shareInstance] getUserIsLogin];
        if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
            [self isLogin];
        }
        else
        {
            MyConsultListViewController *myConsult=[[MyConsultListViewController alloc]initWithNibName:@"MyConsultListViewController" bundle:[NSBundle mainBundle]];
            [self.navigationController pushViewController:myConsult animated:YES];
        }
    }
    else if (indexPath.row==1){
        
        NSString * userIsLogin =  [[UserManager shareInstance] getUserIsLogin];
        if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
            [self isLogin];
        }
        else
        {
            MyPeerListViewController *myPeer=[[MyPeerListViewController alloc]initWithNibName:@"MyPeerListViewController" bundle:[NSBundle mainBundle]];
            [self.navigationController pushViewController:myPeer animated:YES];
        }
    }
    else if (indexPath.row==2){
        NSString * userIsLogin = [[UserManager shareInstance] getUserIsLogin];
        if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
            [self isLogin];
        }
        else{
            [[SystemMessageCenter instance] updataSecretarySystemMessageToReaded];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            SecretaryViewController *secretaryViewController = [[SecretaryViewController alloc]init];
            [self.navigationController pushViewController:secretaryViewController animated:YES];
        }
    }
    else if (indexPath.row == 3){
        NSString * userIsLogin = [[UserManager shareInstance] getUserIsLogin];
        if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
            [self isLogin];
        }
        else{
            [[SystemMessageCenter instance] updataSecretaryNewsMessageToReaded];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
            SubscibeViewController *subscibeViewController = [[SubscibeViewController alloc]init];
            [self.navigationController pushViewController:subscibeViewController animated:YES];
        }
    }
    else {
        
    }
}

#pragma  mark AnhaoDelegate
- (void)skipToConsult
{
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSString * name= userModel.username;
    
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString *mobile_certification=[NSString stringWithFormat:@"%@",[userdefault valueForKey:@"authentication"]];
    if (name.length>0&&[mobile_certification isEqualToString:@"1"]) {
        ConsultViewController *consult=[[ConsultViewController alloc]initWithNibName:@"ConsultViewController" bundle:[NSBundle mainBundle]];
        consult.isFromAnhao=@"1";
        [self.navigationController pushViewController:consult animated:YES];
    }
    else if (name.length>0&&[mobile_certification isEqualToString:@"0"])
    {
        LoginViewController * loginViewController = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
        [self presentViewController:loginViewController animated:YES completion:^{
        }];
        loginViewController.realName.isFromRegist=NO;
        [loginViewController showRealNameView];
    }
    else
    {
        [self isLogin];
    }
    
}
-(void)scrollViewDidScroll:(UIScrollView*)scrollView
{
//    if (kScreenWidth <= 375) { 
    
        if (scrollView.contentOffset.x >= 95){
            self.anhaoHeaderView.rightImage.hidden = YES;
            self.anhaoHeaderView.lefeImageView.hidden = NO;
            
        }else if (scrollView.contentOffset.x <= -1){
            self.anhaoHeaderView.rightImage.hidden = NO;
            self.anhaoHeaderView.lefeImageView.hidden = YES;
        }
//    }
}
- (void)skipToChat:(NSDictionary *)dic
{
    if ([[LCStatusBarOverlay shared] currentVC]) {
        [[[LCStatusBarOverlay shared] currentVC] dismissViewControllerAnimated:YES completion:nil];
        [[LCStatusBarOverlay shared] setCurrentVC:nil];
    }else{
        //返回首页
        if (self.tabBarController.selectedIndex!=0) {
            [self.tabBarController setSelectedIndex:0];
        }else
        {
            [self.navigationController popToRootViewControllerAnimated:NO];
        }
        [self performSelector:@selector(skiptoChatting:) withObject:dic afterDelay:0.1];
    }
    
//    [self skiptoChatting:dic];
}
/**
 *  跳转到聊天页
 *
 *  @param dic 消息内容
 */
- (void)skiptoChatting:(NSDictionary *)dic
{
    
        AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
        if (app.leftView) {
            [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
            }];
        }
        if ([[dic objectForKey:@"type"] intValue] == 1) {
            ConsultingChatViewController *consultChatVC = [[ConsultingChatViewController alloc] init];
            consultChatVC.touid =[dic valueForKey:@"uid"];
            consultChatVC.toTpye = @"1";
            consultChatVC.toMed=@"0";
            consultChatVC.qid=@"0";
            consultChatVC.userName =[dic valueForKey:@"username"];
            consultChatVC.isFromwhere = 0;
            
            [self.navigationController pushViewController:consultChatVC animated:YES];
        }else
        {
            ConsultingChatViewController *consultChatVC = [[ConsultingChatViewController alloc] init];
            consultChatVC.touid =[NSString stringWithFormat:@"%@",[dic valueForKey:@"uid"]];
            consultChatVC.qid=[NSString stringWithFormat:@"%@",[dic valueForKey:@"qid"]];
            consultChatVC.toTpye = @"2";
            consultChatVC.toMed=@"0";
            consultChatVC.userName =[dic valueForKey:@"username"];
            consultChatVC.isFromwhere = 1;
            
            [self.navigationController pushViewController:consultChatVC animated:YES];
        }

}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end
